<!doctype html>
<html>
  <head>
    <title>用户状态调试</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        padding: 20px;
      }
      .info {
        margin: 10px 0;
        padding: 10px;
        background: #f5f5f5;
        border-radius: 4px;
      }
      .true {
        color: green;
        font-weight: bold;
      }
      .false {
        color: red;
        font-weight: bold;
      }
      .refresh-btn {
        margin: 10px 0;
        padding: 10px 20px;
        background: #007bff;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
      }
      .logs {
        margin: 10px 0;
        padding: 10px;
        background: #f8f9fa;
        border-radius: 4px;
        max-height: 200px;
        overflow-y: auto;
        font-family: monospace;
        font-size: 12px;
      }
    </style>
  </head>
  <body>
    <h1>用户状态调试</h1>
    <button class="refresh-btn" onclick="refreshUserInfo()">刷新状态</button>
    <div id="userInfo"></div>

    <h3>存储检查</h3>
    <div id="storageInfo"></div>

    <h3>实时日志</h3>
    <div id="logs" class="logs"></div>

    <script>
      let logs = []

      function log(message) {
        const timestamp = new Date().toLocaleTimeString()
        logs.push(`[${timestamp}] ${message}`)
        if (logs.length > 50) logs = logs.slice(-50) // 保持最新50条
        updateLogs()
      }

      function updateLogs() {
        document.getElementById('logs').innerHTML = logs.join('<br>')
      }

      function checkStorageInfo() {
        const storageData = {
          localStorage: {
            novel_auth_token: localStorage.getItem('novel_auth_token'),
            novel_user_info: localStorage.getItem('novel_user_info'),
            novel_remember_login: localStorage.getItem('novel_remember_login'),
            novel_remembered_email: localStorage.getItem(
              'novel_remembered_email'
            ),
          },
          sessionStorage: {
            novel_auth_token: sessionStorage.getItem('novel_auth_token'),
            novel_user_info: sessionStorage.getItem('novel_user_info'),
          },
        }

        let html = '<h4>LocalStorage:</h4>'
        for (const [key, value] of Object.entries(storageData.localStorage)) {
          html += `<div><strong>${key}:</strong> ${value ? '存在' : '不存在'}</div>`
          if (value && key.includes('user_info')) {
            try {
              const parsed = JSON.parse(value)
              html += `<div style="margin-left: 20px;">用户ID: ${parsed.id}, 用户名: ${parsed.username || '无'}, 邮箱: ${parsed.email || '无'}</div>`
            } catch (e) {
              html += `<div style="margin-left: 20px; color: red;">解析失败: ${e.message}</div>`
            }
          }
        }

        html += '<h4>SessionStorage:</h4>'
        for (const [key, value] of Object.entries(storageData.sessionStorage)) {
          html += `<div><strong>${key}:</strong> ${value ? '存在' : '不存在'}</div>`
        }

        document.getElementById('storageInfo').innerHTML = html
        return storageData
      }

      function checkUserInfo() {
        log('开始检查用户信息...')

        // 从localStorage获取用户信息
        const userToken =
          localStorage.getItem('novel_auth_token') ||
          sessionStorage.getItem('novel_auth_token')
        const userInfo =
          localStorage.getItem('novel_user_info') ||
          sessionStorage.getItem('novel_user_info')

        log(`Token: ${userToken ? '存在' : '不存在'}`)
        log(`User Info: ${userInfo ? '存在' : '不存在'}`)

        let user = null
        if (userInfo) {
          try {
            user = JSON.parse(userInfo)
            log(`解析用户成功: ${JSON.stringify(user)}`)
          } catch (e) {
            log(`解析用户信息失败: ${e.message}`)
          }
        }

        // 模拟权限检查逻辑
        function checkAdmin(user) {
          if (!user) return false
          return (
            user.username === 'admin' ||
            user.username === 'admin_gkl' ||
            user.email === '1477042095@qq.com' ||
            user.nickname === '超级管理员' ||
            user.id === 1 ||
            user.id === '1' ||
            user.id === 3 ||
            user.id === '3'
          )
        }

        const isLoggedIn = !!userToken && !!user
        const isAdmin = checkAdmin(user)

        log(`登录状态: ${isLoggedIn}`)
        log(`管理员状态: ${isAdmin}`)

        document.getElementById('userInfo').innerHTML = `
                <div class="info">
                    <strong>登录状态:</strong> <span class="${isLoggedIn}">${isLoggedIn}</span>
                </div>
                <div class="info">
                    <strong>管理员权限:</strong> <span class="${isAdmin}">${isAdmin}</span>
                </div>
                <div class="info">
                    <strong>用户信息:</strong><br>
                    <pre>${user ? JSON.stringify(user, null, 2) : '未登录'}</pre>
                </div>
                <div class="info">
                    <strong>权限检查详情:</strong><br>
                    ${
                      user
                        ? `
                        - username === "admin": ${user.username === 'admin'}<br>
                        - username === "admin_gkl": ${user.username === 'admin_gkl'}<br>
                        - email === "1477042095@qq.com": ${user.email === '1477042095@qq.com'}<br>
                        - nickname === "超级管理员": ${user.nickname === '超级管理员'}<br>
                        - id === 1: ${user.id === 1}<br>
                        - id === "1": ${user.id === '1'}<br>
                        - id === 3: ${user.id === 3}<br>
                        - id === "3": ${user.id === '3'}
                    `
                        : '用户未登录'
                    }
                </div>
            `
      }

      function refreshUserInfo() {
        logs = [] // 清空日志
        checkUserInfo()
        checkStorageInfo()
      }

      // 监听存储变化
      window.addEventListener('storage', function (e) {
        log(`存储变化: ${e.key} = ${e.newValue}`)
        refreshUserInfo()
      })

      // 初始加载
      refreshUserInfo()

      // 定期检查（每5秒）
      setInterval(() => {
        const currentToken =
          localStorage.getItem('novel_auth_token') ||
          sessionStorage.getItem('novel_auth_token')
        if (currentToken) {
          log('定期检查: 发现token，刷新状态')
          refreshUserInfo()
        }
      }, 5000)
    </script>
  </body>
</html>
